import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:zhaoxiaowu_app/global/global.dart';
import 'package:zhaoxiaowu_app/main.dart';
import 'package:zhaoxiaowu_app/utils/date_utils.dart';
import 'package:zhaoxiaowu_app/utils/rsa/rsa_utils.dart';
import 'package:zhaoxiaowu_app/utils/utils.dart';

class RegisterViewModel extends ChangeNotifier {
  int _gender = 0; // 0 - 男, 1 - 女
  int _solar = 0; // 0 - 阳历, 1 - 阴历
  int _countTime = 0;

  DateTime? _birthDay;

  String get gender => _gender == 0 ? "男" : "女";
  bool get isMale => _gender == 0 ? true : false;

  void setGender(bool newValue) {
    _gender = newValue ? 0 : 1;
    notifyListeners();
  }

  int get countTime => _countTime;

  void setCountTime(int newValue) {
    _countTime = newValue;
    notifyListeners();
  }

  void countDown() {
    _countTime--;
    notifyListeners();
  }

  String get sendMsgCodeText => _countTime > 0 ? "${_countTime.toString()}秒后再次获取" : "获取验证码";

  String get solarText => _solar == 0 ? "阳历" : "阴历";
  bool get isSolar => _solar == 0 ? false : true;

  void setSolar(bool newValue) {
    _solar = newValue ? 1 : 0;
    notifyListeners();
  }

  String get birthDayText => _birthDay != null ? getYMD(_birthDay) : "请选择日期";

  void setBirthDay(DateTime? newValue) {
    print("birthDay = ${newValue ?? "null"}");
    _birthDay = newValue;
    notifyListeners();
  }

  void login(String account, String phone, String msgCode, String password, String name) async {
    ToastUtils.showActivity("正在提交注册信息...");

    String pwd = await RSAUtils.encodeString(password);
    String jsonStr = jsonEncode({
      "username": account,
      "password": pwd,
      "phone": phone,
      "name": name,
      "gender": _gender,
      "birthday": birthDayText,
      "solar": _solar,
    });
    Response result = await Global.shared().post("/zxw/user/register", parameters: {"json": jsonStr});

    print(result);

    if (result.data["success"]) {
      ToastUtils.showSuccess("注册成功");
      if (navigatorKey.currentContext != null) {
        Map<String, String> params = {"account": account, "password": password};
        Navigator.of(navigatorKey.currentContext!).pop(params);
      }
    } else {
      ToastUtils.showError(result.data["msg"]);
    }
  }
}
